﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        try
        {
            string username = txtUsername.Text;
            string password = txtPassword.Text;
            string firstName = txtFirstName.Text;
            string lastName = txtLastName.Text;
            using (var db = new DiaryOnlineDataContext())
            {
                bool isExist = db.Diaries.Any(d => d.Username == username);
                if (isExist)
                {
                    CustomValidator2.ErrorMessage = "Username is exist";
                    CustomValidator2.IsValid = false;
                }
                else
                {
                    Diary d = new Diary
                    {
                        Username = username,
                        Password = password,
                        FirstName = firstName,
                        LastName = lastName,
                        Email = txtEmail.Text
                    };
                    db.Diaries.InsertOnSubmit(d);
                    db.SubmitChanges();
                    Session["Message"] = "Register Successfull";
                    Response.Redirect("Login.aspx");
                }
            }
        }
        catch (Exception ex)
        {
            CustomValidator2.ErrorMessage = ex.Message;
            CustomValidator2.IsValid = false;
        }
    }
}
